package com.laomo.lib_draw_text;

import android.content.Context;
import android.graphics.Bitmap;

import java.util.HashMap;
import java.util.Map;

/**
 * 类说明：
 *
 * @author laomo
 * @date 2024/7/14 00:44
 */
public class DrawTextUtil {

    private static Map<String, DrawTextBean> drawTextBeans = new HashMap<>();
    private static int style = 0;
    private static String fontFilePath;

    public static int getStyle() {
        return style;
    }

    public static String getFontFilePath(){
         return  fontFilePath;
    }

    private static void initTextPaintStyle(){
        for (Map.Entry<String, DrawTextBean> stringDrawTextBeanEntry : drawTextBeans.entrySet()) {
            stringDrawTextBeanEntry.getValue().initTextPaintStyle();
        }
    }

    public static void setFontFilePath(String fontFilePath){
        DrawTextUtil.fontFilePath = fontFilePath;
        initTextPaintStyle();
    }

    //设置粗体
    public static void setBold(boolean isBold) {
        if (isBold) {
            style |= 1;
        } else {
            style &= ~1;
        }
        initTextPaintStyle();
    }

    //设置斜体
    public static void setItalic(boolean isItalic) {
        if (isItalic) {
            style |= 2;
        } else {
            style &= ~2;
        }
        initTextPaintStyle();
    }


    public static byte[] getTextData(Context context, String str, int width, int height, int textHeight) {
        Bitmap textBitmap = createTextBitmap(context, str, width, height, textHeight);
        width = textBitmap.getWidth();
        height = textBitmap.getHeight();
        byte[] bytes = new byte[width * height];


        int color;
        boolean isEmpty;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                color = textBitmap.getPixel(i, j);
                isEmpty = color != 0xffffffff;
                bytes[i * height + j] = (byte) (isEmpty ? 0 : 1);
                //Log.d("lkjdflsd","颜色:"+textBitmap.getPixel(i,j));
            }
        }
        return bytes;
    }

    private static Bitmap createTextBitmap(Context context, String str, int width, int height, int textHeight) {
        return getDrawTextBean(context, width, height, textHeight).getTextBitmap(str, textHeight);
    }


    private static DrawTextBean getDrawTextBean(Context context, int width, int height, int textHeight) {
        String key = "" + width + height;
        DrawTextBean drawTextBean;
        if (drawTextBeans.containsKey(key)) {
            drawTextBean = drawTextBeans.get(key);
        } else {
            drawTextBean = new DrawTextBean(context, width, height, textHeight);
            drawTextBeans.put(key, drawTextBean);
        }
        return drawTextBean;
    }

}